import { createRouter, createWebHistory } from "vue-router";
import { fnAddDynamicMenuRoutes } from "@/util/dynamic-router";
import store from "@/store";

const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("../components/Login/login.vue"),
  },
  {
    path: "/",
    name: "home",
    component: () => import("../views/Home/index.vue"),
    redirect: "/index",
    children: [
      {
        path: "/index",
        name: "index",
        component: () => import("../views/index/index.vue"),
      },
      {
        path: "/userCenter",
        name: "个人中心",
        component: () => import("../views/userCenter/index.vue"),
      },
    ],
  },
];
const router = createRouter({
  history: createWebHistory(),
  routes,
});
// router.beforeEach(() => {
//   // routes[1].children.push(...fnAddDynami/cMenuRoutes(store.state.menuList));
// });

// // 导航守卫
// router.beforeEach((to, from, next) => {
//   //   NProgress.start();
//   if (to.meta.requireAuth) {
//     // 判断该路由是否需要登录权限
//     if (sessionStorage.getItem("token") !== null) {
//       // 判断本地是否存在token
//       next();
//       // 这里是待会获取异步路由的地方
//     } else {
//       // 未登录,跳转到登陆页面
//       next({
//         path: "/login",
//       });
//     }
//   } else {
//     next();
//   }
// });

// 白名单
const whiteList = ["/login", "/index"]; // no redirect whitelist

// 导航守卫
router.beforeEach((to, from, next) => {
  //   NProgress.start();
  try {
    // 判断是否已经获取过动态菜单，未获取，则需要获取一次
    if (store.state.dynamicRoutes.length === 0) {
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        // 判断是否有路由列表，没有继续调用接口获取
        let menus = JSON.parse(sessionStorage.getItem("menuList"));
        store.commit("SET_DYNAMICROUTES", menus);
        let newRoutes = fnAddDynamicMenuRoutes(menus);
        // 循环添加每个路由;
        newRoutes.forEach((route) => {
          router.addRoute("home", route);
        });
        // if ( to.path === "/login") {
        //   next({ path: "/", replace: true });
        // } else {
        // next('/');
        // }
        next({ ...to, replace: true });
      }
    } else {
      // 路由已存在或已缓存路由
      // 判断路由是否需要权限
      if (to.meta.requireAuth) {
        if (localStorage.getItem("access_token") !== null) {
          // 判断本地是否存在token
          next();
        } else {
          // 未登录,跳转到登陆页面
          next({ path: "/login" });
        }
      } else {
        if (whiteList.indexOf(to.path) !== -1) {
          next();
        } else {
          if (localStorage.getItem("access_token") !== null) {
            // 判断本地是否存在token
            next();
          } else {
            // next(`/login?redirect=${to.path}`);
            next({
              path: "/login",
              query: {
                redirect: to.fullPath, // 把要跳转的页面路径作为参数传到登录页面
              },
            });
          }
        }
      }
    }
  } catch (error) {
    next(`/login?redirect=${to.path}`);
  }
});
export default router;
